import { defineStore } from 'pinia';
import api from "@/common/api.js";
//用户信息
export const useUserinfoStore = defineStore('userinfo', {
	state: () => {
		return {
			isLogin: uni.getStorageSync('isLogin') || false, // 是否登录
			accessToken: uni.getStorageSync('accessToken') || '',//token
			userId: uni.getStorageSync('userId') || '',// 用户id
			expireTime: uni.getStorageSync('expireTime') || '',//到期时间
			userInfo: uni.getStorageSync('userInfo') || {}// 用户信息
		}
	},
	actions: {
		//登录成功
		Login(state) {
			uni.setStorageSync("accessToken", state.token);
			uni.setStorageSync("userId", state.userId);
			uni.setStorageSync("expireTime", state.expireTime);
			uni.setStorageSync("isLogin", true);
			this.accessToken = state.token
			this.userId = state.userId
			this.expireTime = state.expireTime
			this.isLogin = true
		},
		//退出登录
		Logout() {
			api.Getlogout_API().then(res => {
				if (res.code == 10000) {
					this.accessToken = ''
					this.userId = ''
					this.expireTime = ''
					this.isLogin = false
					this.userInfo = {}
					uni.removeStorageSync("userInfo");
					uni.removeStorageSync("accessToken");
					uni.removeStorageSync("userId");
					uni.removeStorageSync("expireTime");
					uni.removeStorageSync('isGoods')
					uni.removeStorageSync('isStore')
					uni.setStorageSync("isLogin", false);
					uni.switchTab({
						url: '/pages/main/main',
					})
				}
			})

		},
		//获取用户信息
		GetUserInfo() {
			return new Promise((resolve, reject) => {
				api.GetUserInfo_API().then(res => {
					if (res.code == 0) {
						this.userInfo = res.data
						uni.setStorageSync("userInfo", res.data)
						resolve(res.data)
					}
				}).catch(err => {
					reject(err)
				})
			})
		},
		// 白名单
		getWhiteList() {
			return new Promise((resovle, reject) => {
				// 判断白名单是否开启
				api.getwhite_API().then((res) => {
					const isOpen = res.data || 0
					uni.setStorageSync('isOpen', isOpen)
					if (isOpen) {
						// 获取白名单
						api.getList_API().then(res => {
							const data = res.data || []
							uni.setStorageSync('whiteList', data)
						})
					}
				});
			})
		}
	}
});
